const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:0,
    addrId:0,
    orderId:0,
    buyType:"",
    orderData:"",
    countDownStatus:false,
    showCountDown:false,
    ms:900000,
    countDownText:'00:00:00',
    payStatus:false, //保存是否支付
    showPrice:""
  },
  //增加购买数量
  add(){
    let that = this;
    let count = that.data.orderData.num;
    let max = that.data.orderData.inventory;
    if (count >= max){
      app.showToast('不能超过最大库存')
    }else{
      that.setData({
        'orderData.num': ++count
      })
      that.setData({
        showPrice: parseFloat(that.data.orderData.num * that.data.orderData.money + that.data.orderData.freight).toFixed(2)
      })
    }
  },
  //增加减少数量
  minus(){
    let that = this;
    let count = that.data.orderData.num;
    that.setData({
      'orderData.num': count == 1 ? count = 1 : --count
    })
    that.setData({
      showPrice: parseFloat(that.data.orderData.num * that.data.orderData.money + that.data.orderData.freight).toFixed(2)
    })
  },
  //买家留言
  remarkIpt(e){
    this.setData({
      'orderData.remark':e.detail.value
    })
  },
  // 去支付
  goPay(){
    let that = this;
    if (!that.data.addrId){ 
      app.showToast('请添加收货地址')
      return 
    }
    wx.showLoading({
      title: '调取微信支付',
    })
    if (that.data.orderId == 0){
      wx.request({
        url: app.buildUrl('/order/add-order'),
        header: app.buildHeader(),
        method: "POST",
        data: {
          shop_id: that.data.orderData.shop.id,
          address_id: that.data.orderData.address[0].id,
          order_type: that.data.buyType,
          goods_num: that.data.orderData.num,
          active_id: that.data.orderData.active_id,
          goods_attr_id: that.data.orderData.goods_attr_id,
          goods_id: that.data.orderData.goods_id,
          goods_price: that.data.orderData.num * that.data.orderData.money,
          freight: that.data.orderData.freight,
          remark: that.data.orderData.remark
        },
        success(res) {
          if (res.data.code == 200) {
            that.setData({
              orderId: res.data.data
            })
            that.payFun(res.data.data)
          } else {
            app.showToast(res.data.msg)
          }
        }
      })
    } else {
      wx.request({
        url: app.buildUrl('/order/update-order'),
        header: app.buildHeader(),
        method: "POST",
        data: {
          shop_id: that.data.orderData.shop.id,
          order_id: that.data.orderId,
          address_id: that.data.orderData.address[0].id,
          order_type: that.data.buyType,
          goods_num: that.data.orderData.num,
          active_id: that.data.orderData.active_id,
          goods_attr_id: that.data.orderData.goods_attr_id,
          goods_id: that.data.orderData.goods_id,
          goods_price: that.data.orderData.num * that.data.orderData.money,
          freight: that.data.orderData.freight,
          remark: that.data.orderData.remark
        },
        success(res) {
          if (res.data.code == 200) {
            that.payFun(that.data.orderId)
          } else {
            app.showToast(res.data.msg)
          }
        }
      })
    }
  },
  //关闭支付
  closePay() {
    this.setData({
      showCountDown: false
    })
  },
  //继续支付
  goPay2(){
    let that = this;
    wx.showLoading({
      title: '调取微信支付',
    })
    that.closePay();
    that.payFun(that.data.orderId)
  },
  //支付Fun
  payFun(orderId){
    let that = this;
    wx.request({
      url: app.buildUrl('/pay/pay-order'),
      header: app.buildHeader(),
      data: {
        order_id: orderId
      },
      success(res) {
        wx.hideLoading()
        if(res.data.code == 200){
          wx.requestPayment({
            'timeStamp': res.data.data.timeStamp + '',
            'nonceStr': res.data.data.nonceStr,
            'package': res.data.data.package,
            'signType': res.data.data.signType,
            'paySign': res.data.data.paySign,
            success(res) {
              console.log(res)
              app.showToast('支付成功', 'success')
              that.setData({
                payStatus: true
              })
              wx.redirectTo({
                url: '../success/success?id=' + orderId,
              })
            },
            fail(res) {
              that.setData({
                showCountDown: true,
                payStatus: false
              })
              if (that.data.countDownStatus) { return } //如果已经开始倒计时
              that.setData({
                endTime: new Date().getTime() + that.data.ms,
                countDownStatus: true
              })
              app.countDown({
                date: that.data.endTime,
                fun: (options) => {
                  that.setData({
                    countDownText: `${options.h}:${options.m}:${options.s}`
                  })
                }
              })
            }
          })
        }else{
          app.showToast(res.data.msg)
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.setData({
      orderId: options.orderId || 0,
      id: options.id,
      'orderData.num': options.num,
      buyType: options.type
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    let that = this;
    that.setData({
      showCountDown:false
    })
    wx.request({
      url: app.buildUrl('/active/payment-info'),
      header: app.buildHeader(),
      data: {
        'addr_id': that.data.addrId,
        'attr_id': that.data.id,
        'num': that.data.orderData.num,
        'type': that.data.buyType
      },
      success(res) {
        if (res.data.code == 200) {
          let data = res.data.data;
          data.freight = parseFloat(data.freight)
          that.setData({
            orderData: data,
            'orderData.remark':"",
            showPrice: parseFloat(data.num * data.money + data.freight).toFixed(2),
            addrId: data.address.length == 0 ? 0 : data.address[0].id
          })
        } else {
          app.showToast(res.data.msg)
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    
    if (!that.data.payStatus) {
      wx.showModal({
        title: '确定要放弃付款吗？',
        content: '您尚未完成支付，选中的商品可能被其他人抢走哦~',
        cancelText: '暂时放弃',
        cancelColor: '#6e6e6e',
        confirmText: '继续支付',
        confirmColor: '#ff0277',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../pay/pay?id=' + that.data.id + '&type=' + that.data.buyType + '&num=' + that.data.orderData.num + '&orderId=' + that.data.orderId,
            })
          }
        }
      })
    }
  }
})